import { clearJson } from '@utils'

import { listApi } from '@/api/conversation'

export const useConversationStore = defineStore('conversation', {
  state: () => ({
    active: null,
    list: [],
  }),
  getters: {
    hasUnread: ({ list }) => {
      return list.some(item => item.unread > 0)
    }
  },
  actions: {
    /**
     * 获取会话列表
     * @param {*} params
     * @returns
     */
    async getList() {
      const r = await listApi()
      console.log('获取会话列表API返回:', r)
      if (r) {
        // 确保每个会话对象都有正确的结构和属性
        const processedList = r.data.map(item => {
          // 处理群聊情况
          if (item.group) {
            // 确保 group 对象有正确的属性
            const group = {
              ...item.group,
              id: item.group.id,
              name: item.group.name || '群聊',
              avatar: item.group.avatar || '',
              // 优先使用 ownerId，如果不存在则使用 creator_id
              ownerId: item.group.ownerId || item.group.creator_id || null
            }
            return {
              ...item,
              unread: item.unread || 0,
              type: 'group',
              group
            }
          }
          // 处理私聊情况
          return {
            ...item,
            unread: item.unread || 0,
            type: 'friend'
          }
        })
        
        this.list = processedList
        console.log('处理后的会话列表:', this.list)
      }
    },
    /**
     * 新增会话 存在则更新消息
     * @param {*} conversation 
     */
    addConversation(conversation) {
      const { roomId, message } = conversation
      const exist = this.list.find(item => item.roomId === roomId) 
      if (exist) {
        
        exist.message = message
        // 如果不是当前活跃的会话，增加未读消息数
        if (!this.active || this.active.roomId !== roomId) {
          exist.unread = (exist.unread || 0) + 1
        }
      } else {
        console.log(`添加新会话 ${roomId}, 消息ID: ${message.id}`)
        this.list.unshift(conversation)
      }
    },
    /**
     * 更新消息
     * @param {*} id 消息ID
     * @param {*} conversation 会话
     */
    updateMessage(messageId, conversation){
      for (let i = 0; i < this.list.length; i++) {
        const row = this.list[i];
        if (messageId === row.message.id){
          row.message = conversation.message
          return
        }
      }
    },
    /**
     * 设置未读
     * @param {*} id 
     */
    setUnread(id) {
      const conversation = this.list.find(item => item.id === id)
      if (conversation.unread) {
        conversation.unread += 1
      } else {
        conversation.unread = 1
      }
    },
    /**
     * 设置已读
     * @param {*} id 
     * @returns 
     */
    setRead(id) {
      const conversation = this.list.find(item => item.id === id)
      if (conversation) {
        conversation.unread = 0
        return conversation
      } else {
        console.error('未找到 ID 为', id, '的会话对象')
        return {}
      }
    },
    /**
     * 设置选中
     * @param {*} conversation 
     */
    setActive(conversation) {
      // 如果参数为null或undefined，直接设置active为null并返回
      if (!conversation) {
        this.active = null;
        console.log('清除当前活跃会话');
        return;
      }
      
      // 获取会话ID
      const id = conversation.id;

      const existingConversation = this.list.find(item => item.id === id);
      
      if (existingConversation) {
        // 设置为已读
        existingConversation.unread = 0;
        
        console.log('会话对象是否有 group 属性:', !!existingConversation.group);
        console.log('会话对象 group 属性类型:', typeof existingConversation.group);
        console.log('会话对象是否有 friend 属性:', !!existingConversation.friend);

        // 如果friend为null且没有group属性，则为群聊，需要创建group对象
        if (!existingConversation.friend && !existingConversation.group) {
          existingConversation.group = {
            id: existingConversation.roomId,
            name: '群聊',
            avatar: '',
            ownerId: null // 默认为null，避免类型错误
          };
        }
        // 如果有group属性但没有ownerId，确保设置为null而不是undefined
        if (existingConversation.group && existingConversation.group.ownerId === undefined) {
          existingConversation.group.ownerId = existingConversation.group.creator_id || null;
        }
        
        this.active = existingConversation;
      } else {
        // 如果在列表中没找到，则直接使用传入的conversation参数
        this.active = conversation;
      }
      
      console.log('设置 active 后的结果:', this.active);
    },
    /**
     * 更新用户在线状态
     * @param {*} userId 用户ID
     * @param {*} online 在线状态
     */
    updateUserOnline(userId, online) {
      for (let i = 0; i < this.list.length; i++) {
        const { friend } = this.list[i];
        if (friend && friend.userId === userId) {
          friend.online = online
          break
        }
      }
    },
    /**
     * 清除数据
     */
    clear() {
      clearJson(this.$state)
    }
  }
})
